package com.yzw.phonestoreservice.controller;


import com.yzw.phonecommen.common.R;
import com.yzw.phonecommen.constant.SystemConstant;
import com.yzw.phonestoreservice.annotation.UnInterception;
import com.yzw.phonestoreservice.pojo.User;
import com.yzw.phonestoreservice.service.UserService;
import com.yzw.phonecommen.utils.JwtUtils;
import com.yzw.phonestoreservice.vo.LoginVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @date 2022/11/2
 * @desc
 */
@RestController
@RequestMapping("/phone/user")
public class UserController {

    @Autowired
    private UserService userService;
    @PostMapping("/login")
    @UnInterception
    public R login(@RequestBody LoginVo loginVo){
        //
        User currentUser = userService.login(loginVo);
        if (currentUser!=null){
            String token = JwtUtils.createJWT(String.valueOf(currentUser.getId()), currentUser.getUsername(), SystemConstant.JWT_TTL);
            return R.ok().data("token",token);
        } else {
            return  R.error().message("用户名或密码错误");
        }
    }

    @GetMapping("/info")
    public R info(String token){
        HashMap<Object, Object> map = new HashMap<>();
        try {
            Claims claims = JwtUtils.parseJWT(token);
            String id = claims.getId();
            int userId = Integer.parseInt(id);
            String userName = claims.getSubject();
            User currentUser = userService.infoById(userId);
            map.put("roles","['admin']");
            map.put("introduction","I am a super administrator");
//            头像
            map.put("avatar",currentUser.getPic());
            map.put("name",userName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().data(map);
    }
    @GetMapping("/logout")
    public R logout(){
        return R.ok();
    }


}
